package com.github.rpc4j.producer.core;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.github.rpc4j.producer.config.Rpc4jProducerConfig;
import com.github.rpc4j.producer.exception.Rpc4jServiceException;
import com.github.rpc4j.producer.network.NettyProducer;
import com.github.rpc4j.producer.network.Producer;
import com.github.rpc4j.producer.service.Rpc4jServicePool;
import com.github.rpc4j.producer.service.ServicePool;
import com.github.rpc4j.producer.zk.ZkUtil;

public class Rpc4jProducerService {
	private static Logger logger = Logger.getLogger(Rpc4jProducerService.class);

	public static final int DEFAULE_RPC_PORT = 1292;
	private String zkServer;
	private int rpcPort = DEFAULE_RPC_PORT;
	private String id;

	private Rpc4jProducerConfig config;

	private Rpc4jProducerContext context = new Rpc4jProducerContext();

	private ServicePool servicePool = null;

	public void setZkServer(String zkServer) {
		this.zkServer = zkServer;
	}

	public void setRpcPort(int rpcPort) {
		this.rpcPort = rpcPort;
	}

	public void setId(String id) {
		this.id = id;
	}

	public Rpc4jProducerContext getContext() {
		return context;
	}

	public Rpc4jProducerService() {
		
	}

	public void init() {
		try {
			config();
            start();
		} catch (Exception e) {
			logger.error(e);
			throw new Rpc4jServiceException("rpc4j producer init error,",e);
		} finally {
		}

	}
	
	private void config(){
		this.config = new Rpc4jProducerConfig();
		config.setId(id);
		config.setRpcPort(rpcPort);
		config.setZkServer(zkServer);
		context.setConfig(config);
		servicePool = new Rpc4jServicePool(context);
		context.setServicePool(servicePool);
	}

	private void start() {
		initZk();
		initSever();
	}

	private void initZk() {
		if (StringUtils.isBlank(config.getZkServer()))
			return;
		ZkUtil zkUtil = new ZkUtil(config);
		zkUtil.init();
		context.setZkUtil(zkUtil);
	}

	private void initSever() {
		Producer producer = new NettyProducer(context);
		producer.init();
	}

}
